package org.jgs1904.quickstart.service.impl;

import org.jgs1904.quickstart.service.CustomPermissionService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @author: 默苍璃
 * @date: 2025-06-0910:19
 */
@Component
public class CustomPermissionServiceImpl implements CustomPermissionService {

    /**
     * 判断当前用户是否有权限访问当前请求的URI
     *
     * @param request
     * @param authentication
     * @return
     */
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object obj = authentication.getPrincipal();
        if (obj instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) obj;
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

            /**
             * 构造一个新的 SimpleGrantedAuthority，使用当前请求的 URI 作为权限名称；
             * 检查用户权限集合中是否包含这个权限；
             * 如果存在，返回 true 表示有权限访问；否则返回 false。
             */
            String requestURI = request.getRequestURI();
            System.out.println(requestURI);
            return authorities.contains(new SimpleGrantedAuthority(requestURI));
        }
        return false;
    }

}
